package com.shuyuwl.service.impl;

import com.shuyuwl.core.service.impl.DaoServiceImpl;
import com.shuyuwl.core.support.ServerResponse;
import com.shuyuwl.domain.File;
import com.shuyuwl.repository.FileRepository;
import com.shuyuwl.service.FileService;
import com.shuyuwl.utils.FastFileUploadUtil;
import com.shuyuwl.vo.FileVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 数驭未来文件管理中心
 * @author xpk
 * @date 2019/10/30
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class FileServiceImpl extends DaoServiceImpl<File,Long, FileRepository> implements FileService {
    @Autowired
    private FileRepository fileRepository;

    @Override
    public File isFile(String sha1) {
        return fileRepository.findBySha1(sha1);
    }

    @Override
    public File save(File file){
        return fileRepository.save(file);
    }

    @Override
    public void deleteByPath(String path) {
        fileRepository.deleteByPath(path);
    }

    @Override
    public ServerResponse<FileVo> uploadFile(MultipartFile multipartFile) {
        try {
            File file = FastFileUploadUtil.saveToFastDfsAndDatabase(multipartFile);
            FileVo vo = new FileVo();
            BeanUtils.copyProperties(file,vo);
            return ServerResponse.createBySuccess("上传文件成功",vo);
        } catch (BeansException e) {
            return ServerResponse.createByErrorMessage("上传失败");
        }
    }

    @Override
    public File getById(Long id) {
        return repository.getOne(id);
    }

    @Override
    public File getByPath(String path) {
        return repository.findAllByPath(path);
    }
}
